package com.derbysoft.synxisadapter.dswitch2.service.impl;

import com.derbysoft.synxisadapter.commons.model.OperationType;
import com.derbysoft.synxisadapter.commons.repository.ReservationRepository;
import com.derbysoft.synxisadapter.commons.repository.TransactionLogRepository;
import com.derbysoft.synxisadapter.dswitch2.service.TransactionLogService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;

public class TransactionLogServiceImpl implements TransactionLogService {
    private TransactionLogRepository transactionLogRepository;

    private ReservationRepository reservationRepository;

    private ExecutorService executorService;

    private Set<OperationType> needLogOperationTypeSet = new HashSet<OperationType>();

    @Override
    public void create(final LogInfo logInfo) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (needLogOperationTypeSet.contains(logInfo.getOperationType()) ||
                        logInfo.hasError()) {
                    transactionLogRepository.create(logInfo.toTransactionLog());
                }

                if (logInfo.isReservation()) {
                    String erspCode = logInfo.getErspCode();
                    String hotelPassport = logInfo.getHotelPassport();

                    reservationRepository.appendLog(erspCode, hotelPassport,
                            logInfo.toReservationLog(), logInfo.getTimestamp());
                }
            }
        });
    }

    public void setTransactionLogRepository(TransactionLogRepository transactionLogRepository) {
        this.transactionLogRepository = transactionLogRepository;
    }

    public void setExecutorService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public void setReservationRepository(ReservationRepository reservationRepository) {
        this.reservationRepository = reservationRepository;
    }

    public void setNeedLogOperationTypes(List<String> needLogOperationTypes) {
        for (String needLoggingOperationType : needLogOperationTypes) {
            this.needLogOperationTypeSet.add(OperationType.valueOf(needLoggingOperationType));
        }
    }
}
